<?php

namespace app\admin\controller\xykeep;

use app\common\controller\Backend;
use fast\Tree;
use app\admin\library\Auth;

use think\Db;
use Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分类管理
 */
class Category extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\admin\model\xykeep\Category');

        $auth = Auth::instance();
        $admin_info = $auth->getUserInfo();
        $this->store_id = $admin_info['store_id'];
        $this->assign('store_id',$this->store_id);

        $tree = Tree::instance();
        $tree->init(collection($this->model->where(['store_id'=>$this->store_id])->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $typeList = $this->model->getTypeList();
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $typeList);

    }


    /**
     * 查看
     */
    public function index($type = '')
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            $search = $this->request->get("search");
            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assignconfig('type',$type);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add($type = '')
    {

        if (false === $this->request->isPost()) {
            $list = [];
            foreach ($this->categorylist as $k => $v) {
                if ($v['type'] == $type) {
                    $list[] = $v;
                }
            }
            $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
            foreach ($list as $k => $v) {
                $categorydata[$v['id']] = $v;
            }
            $this->view->assign('parentList',$categorydata);
            $this->assignconfig('type',$type);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['store_id'] = $this->store_id;
            $params['type'] = $type;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $list = [];
            foreach ($this->categorylist as $k => $v) {
                if ($v['type'] == $row['type']) {
                    $list[] = $v;
                }
            }
            $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
            foreach ($list as $k => $v) {
                $categorydata[$v['id']] = $v;
            }
            $this->view->assign('parentList',$categorydata);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 选择
     */
    public function select($type = '')
    {
        if ($this->request->isAjax()) {
            return $this->index($type);
        }
        $this->assignconfig('type',$type);
        return $this->view->fetch();
    }
}
